package com.newflypig.jblog.util;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class DESUtil {
	
	private static byte[] crypt(byte[] data, byte[] key, int mode) throws Exception {
		// 生成一个可信任的随机数源
		SecureRandom sr = new SecureRandom();
		// 从原始密钥数据创建DESKeySpec对象
		DESKeySpec dks = new DESKeySpec(key);
		// 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey securekey = keyFactory.generateSecret(dks);
		// Cipher对象实际完成解密操作
		Cipher cipher = Cipher.getInstance("DES");
		// 用密钥初始化Cipher对象
		cipher.init(mode, securekey, sr);
		return cipher.doFinal(data);
	}
	
	/**
	 * DES解密
	 * @param 密文
	 * @return 明文
	 */
	public static String decryptString(String data){
		if (data == null || "".equals(data))
            return "";
		String str=null;
		try {
			str=new String(crypt(new BASE64Decoder().decodeBuffer(data),BlogConfig.DESKEY.getBytes(),Cipher.DECRYPT_MODE));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return str;
	}
	
	/**
	 * 加密
	 * @param 明文
	 * @return 密文
	 */
	public static String encryptString(String data){
        if(data==null || "".equals(data))
        	return "";
		String str=null;
        try {
			str=new BASE64Encoder().encode(crypt(data.getBytes(), BlogConfig.DESKEY.getBytes(), Cipher.ENCRYPT_MODE));
		} catch (Exception e) {
			e.printStackTrace();
		}
        return str;
	}
}
